package edu.upenn.seas.peerreview.smui.variants

import edu.upenn.seas.peerreview.Id
import scala.collection.mutable

/**
 * Maps an Id to a (possibly) shorter canonical name.
 */
trait IdMapper {
  /**
   * A mapping from Id to String. Assigns a "canonical name" for each Id, so
   * it is easier to select/name an opponent.
   */
  var idToString : mutable.Map[Id, String] = null;

  /**
   * Creates a mapping of Id->String. This is expected to be called only once
   * per game, when the opponent list is first received.
   * 
   * <p>The implementation must ensure that each String identifier is unique.
   * For now, this just does Player[#], because we cannot rely on the structure
   * of the Id class for anything. Ideally (in the future), the BSManager will
   * provide a means with which to provide an Id-to-name mapping.
   * 
   * @param opponents the list of opponent ids
   */
  protected def makeMapping(opponents : List[Id]) {
    idToString = mutable.Map()
    idToString ++ opponents.zipWithIndex.map( 
      tup => (tup._1, IdMapper.makeCanonicalString(tup._2, tup._1))
    )
  }

  /**
   * Return the string mapping.
   */
  protected def mapId(id: Id) = idToString(id)
}

object IdMapper {
  /**
   * @VisibleForTesting
   */
  def makeCanonicalString(index: Int, id: Id) = {
    val str = id.toString
    "P" + index + (if (str.indexOf(".") != -1)
        str.substring(str.indexOf(".")) else "")  
  }
}